import { ref, watch } from 'vue'

/**
 * @param {object}   options
 * @param {object}   options.initialValue
 * @param {number}   options.initialValue.total
 * @param {number}   options.initialValue.pageSize
 * @param {number}   options.initialValue.currentPage
 * @param {number[]} options.initialValue.pageSizes
 * @param {Function} options.onSizeChange
 * @param {Function} options.onCurrentChange
 * @param {Function} options.onChange 除了total，值改变了都会触发，第一个参数为触发的属性
 */
export function usePagination(options) {
  const { initialValue, onChange, onSizeChange, onCurrentChange } =
    options || {}
  const total = ref(initialValue?.total ?? 0)
  const pageSizes = ref(initialValue?.pageSizes ?? [10, 20, 50, 100])

  const pageSize = ref(initialValue?.pageSize ?? 10)
  const currentPage = ref(initialValue?.currentPage ?? 1)

  watch(pageSize, (...args) => {
    onSizeChange?.(...args)
    onChange?.('pageSize', ...args)
  })
  watch(currentPage, (...args) => {
    onCurrentChange?.(...args)
    onChange?.('currentPage', ...args)
  })

  return {
    total,
    pageSize,
    currentPage,
    pageSizes
  }
}
